import { Effect, ImmerReducer,history } from 'umi'
import { loginReq } from '@/service/login'
import { getCookies, setCookies } from '@/utils/cookies'
import {message} from 'antd'
export interface ILoginState {
    loginState: boolean
    adminname: string
    token: string
    role: string
}
export interface ILoginModel {
    // 命名空间写的和 正式定义时一致
    namespace: 'login'
    state:ILoginState,
    effects:{
        login:Effect
    },
    reducers:{
        // LOGIN: Reducer<ILoginState>
        // 启用 immer 之后
        LOGIN: ImmerReducer
    }
}
const loginModel: ILoginModel = {
    namespace:'login',
    state: {
        loginState: getCookies('loginState') === 'true' || false,
        adminname: getCookies('adminname') || '',
        token: getCookies('token') || '',
        role: getCookies('role') || '1'
    },
      // 处理 异步操作，类似于vue的actions
    effects:{
        // 如何解决异步操作：回调函数，promise，async/await
        // effects 中使用es6的 generator 解决异步操作问题 ，需要配合 yield 解决问题
        // * ===> async    yield ===> await
        *login({payload},{call,put}){
            // payload 代表就是参数
            // call 代表调用异步操作 ------
            // put 代表触发改变reducer ----- dispatch
            const res = yield call(loginReq,payload)
            console.log(res)
            if(res.code === '10005' || res.code === '10003'){
                message.error('输入信息有误')
                return
            }
            setCookies('loginState','true')
            setCookies('adminname',res.data.adminname)
            setCookies('role',res.data.role)
            setCookies('token',res.data.token)
            history.push('/home')
            yield put({
                type:'LOGIN',
                payload: res.data
            })
        }
    },
      // 修改状态的，类似于vue的mutations
    reducers:{
        LOGIN(state, action){
            console.log(action,123);
            state.adminname = action.adminname
            state.role = action.role
            state.token = action.token
        }
    }
}
export default loginModel